﻿using QiuShiBaiKe.BLL;
using QiuShiBaiKe.Commons;
using QiuShiBaiKe.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace QiuShiBaiKe.Web.Controllers
{
    public class MessageController : Controller
    {
        public ActionResult Index(long? id)
        {
            if (id == null)
            {
                //写成View("Error", "id不能为空");
                //就匹配成这个这个重载：ViewResult View(string viewName, string masterName)
                //如果当前Views下没有Error.cshtml，则会去Shared下去找
                return View("Error", (object)"id不能为空");
            }
            Message msg = new MessageBLL(WebHelper.DbContext).GetById((long)id);
            return View(msg);
        }


        public ActionResult ShowPostMessage()
        {
            User currentUser = WebHelper.GetLoginedUser(HttpContext);
            if (currentUser == null)
            {
                WebHelper.SetLoginDestinationUrl(HttpContext);
                return RedirectToAction("ShowLogin", "User");
            }
            return View();
        }

        public ActionResult PostMessage(FormCollection fc)
        {
            User currentUser = WebHelper.GetLoginedUser(HttpContext);
            if (currentUser == null)
            {
                WebHelper.SetLoginDestinationUrl(HttpContext, "/Message/ShowPostMessage");
                return View("Error", (object)"请先<a href='/User/ShowLogin'>登陆</a>");
            }
            string msg = fc["msg"];
            if (string.IsNullOrEmpty(msg))
            {
                return View("Error", (object)"请填写要发表的文字");
            }

            bool isAnonymous = (fc["isAnonymous"] == "on");
            var imgFile = Request.Files["imgFile"];
            string imageUrl = null;
            if (imgFile.ContentLength > 0)//如果用户上传了图片
            {
                if(imgFile.ContentLength>2*1024*1024)
                {
                    return RedirectToAction("Error", (object)"图片最大允许1MB");
                }
                string fileExt = Path.GetExtension(imgFile.FileName).ToLower();
                if(fileExt!=".jpg"&&fileExt!=".png"&&fileExt!=".jpeg"&&fileExt!=".gif")
                {
                    return RedirectToAction("Error", (object)"只允许如下格式的图片：jpg、jpeg、png、gif");
                }

                DateTime now = DateTime.Now;
                //计算文件的保存文件夹下
                //用年/月/日做文件目录，这样避免一个文件夹下文件过多问题
                //用文件的MD5值做文件名，这样避免多次上传同一副图片造成磁盘浪费
                string fileName = "/Upload/"+now.Year+"/"+now.Month+"/"+now.Day+"/"
                    + CommonHelper.CalcMD5(imgFile.InputStream)+fileExt;
                imgFile.InputStream.Position = 0;
                string imgFileFullPath = Server.MapPath("~" + fileName);
                Directory.CreateDirectory(Path.GetDirectoryName(imgFileFullPath));//如果文件夹不存在，则先创建文件夹
                imgFile.SaveAs(imgFileFullPath);

                imageUrl = fileName;
            }
            MessageBLL msgBll = new MessageBLL(WebHelper.DbContext);
            long msgId = msgBll.Add(currentUser.Id, msg, isAnonymous, imageUrl);
            return RedirectToAction("Index", "Message", new { id = msgId });
        }

        private const string MESSAGE_TOTALCOUNT = "Message.TotalCount";

        /// <summary>
        /// 显示某一页的糗事列表
        /// </summary>
        /// <param name="pageIndex">页码，从1开始</param>
        /// <returns></returns>
        public ActionResult Page(int pageIndex)
        {
            if (pageIndex <= 0)
            {
                return View("Error", (object)"pageIndex必须>0");
            }
            MessageBLL msgBll = new MessageBLL(WebHelper.DbContext);

            //尝试从缓存中获取总条数，避免频繁查询总条数给数据库带来的压力
            //总糗事条数
            int? totalCount = (int?)HttpContext.Cache[MESSAGE_TOTALCOUNT];
            if (totalCount == null)
            {
                totalCount = msgBll.GetMessagesCount();
                HttpContext.Cache.Insert(MESSAGE_TOTALCOUNT, totalCount, null, 
                    DateTime.Now.AddSeconds(10), TimeSpan.Zero);//缓存10秒钟
            }

            int pageSize = 10;//一页显示几条Message        
            Message[] msgs = msgBll.GetMessages(pageIndex, pageSize);
            ViewBag.pageIndex = pageIndex;
            ViewBag.pageSize = pageSize;
            ViewBag.totalCount = totalCount;
            return View(msgs);
        }
    }
}
